<template>
  <div class="page-content">
    <a-card class="cards" v-if="!showDetail">
      <div class="header">
        <Condition
          :condition="condition"
          :btns="['search', 'reset']"
          @search="searchHandle"
          @reset="reset"
        />
        <div style="display: flex; align-items: center; justify-content: space-between">
          <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
          <a-button type="primary" @click="addOrUpdateHandle()">新建服务组</a-button>
        </div>
      </div>
      <div class="main">
        <a-table
          class="table"
          size="small"
          :loading="loading"
          :dataSource="List"
          :columns="columns"
          :pagination="pagination"
          @change="paginationChange"
          :sticky="{ offsetHeader: 0 }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex == 'no'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>
            <template v-if="column.dataIndex == 'memberList'">
              {{ memberList(record.memberList) }}
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-button type="link" @click="patientInfoHandle(record)">查看</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
    <PatientInfo ref="patientInfoRef" v-else @close="goBack" />
    <a-modal width="720px" v-model:open="modalOpen" title="新建服务组" :maskClosable="false">
      <div class="modalChat">
        <a-form
          class="modelForm"
          ref="formRef"
          :rules="rules"
          :colon="false"
          :model="formState"
          :label-col="{ style: { width: '110px' } }"
          labelAlign="left"
        >
          <a-form-item label="服务组名称" name="groupName" required>
            <a-input
              style="width: 350px"
              v-model:value="formState.groupName"
              autocomplete="off"
              :maxlength="20"
              placeholder="请输入服务组名称"
            />
          </a-form-item>
          <a-form-item label="组长" name="groupLeader" required>
            <a-select
              style="width: 350px"
              v-model:value="formState.groupLeader"
              showSearch
              allowClear
              :filterOption="filterOption"
              placeholder="请选择组长，组长需负责管理路径"
              @dropdownVisibleChange="dropdownVisibleChange(1)"
            >
              <a-select-option
                v-for="(item, index) in creatorList"
                :label="item.label"
                :key="index"
                :disabled="item.disabled"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="其他成员" name="otherMembers" required>
            <a-select
              style="width: 350px"
              v-model:value="formState.otherMembers"
              showSearch
              allowClear
              :filterOption="filterOption"
              mode="multiple"
              :max-tag-count="3"
              placeholder="请选择其他成员"
              @dropdownVisibleChange="dropdownVisibleChange(2)"
            >
              <a-select-option
                v-for="(item, index) in creatorListTwo"
                :label="item.label"
                :key="index"
                :disabled="item.disabled"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <div class="tips" style="padding-left: 20px; color: #c72a29">
            提示：服务组创建成功后不可编辑、删除，请确认后提交
          </div>
        </a-form>
      </div>
      <template #footer>
        <a-button @click="modalOpen = false">取消</a-button>
        <a-button type="primary" :loading="modalLoading" @click="modalConfirm">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import Condition from '@/components/ConditionSearch/index.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { imgroupPage, imgroupCreate } from '@/api/memberOrder/index'
import { getAllUser } from '@/api/healthManaWorkbench/index'
import { ExclamationCircleFilled, CheckCircleFilled } from '@ant-design/icons-vue'
import message from 'ant-design-vue/es/message'
import PatientInfo from './detail.vue'
import { useDict } from './components/getDict'
import dayjs from 'dayjs'
const loading = ref<boolean>(false)
const showDetail = ref(false)
const patientInfoRef = ref()
const List = ref<any[]>([])
const templateType = '健康处方'
const formRef = ref()
// let { creatorList } = useDict(templateType)
const creatorList = ref([])
const creatorListTwo = ref()
const formState = reactive({
  groupName: '',
  groupLeader: [],
  otherMembers: []
})
const rules = ref({
  groupName: [{ required: true, message: '请输入服务组名称', trigger: 'blur', whitespace: true }],
  groupLeader: [{ required: true, message: '请选择组长，组长需负责管理路径', trigger: 'change' }],
  otherMembers: [{ required: true, message: '请选择其他成员', trigger: 'change' }]
})
const condition = ref([
  //   {
  //     title: '订单创建时间',
  //     dataIndex: 'createTime',
  //     type: 'dayRange',
  //     value: [],
  //     showTime: true,
  //     style: { width: '340px' }
  //   },
  //   {
  //     title: '',
  //     dataIndex: 'payOrderNo',
  //     type: 'input',
  //     value: '',
  //     placeholder: '请输入微信订单号'
  //   },
  //   {
  //     title: '',
  //     dataIndex: 'bizOrderNo',
  //     type: 'input',
  //     value: '',
  //     placeholder: '请输入商户订单号'
  //   },
  {
    title: '',
    dataIndex: 'groupName',
    type: 'input',
    value: '',
    placeholder: '请输入组名/成员姓名'
  }
])
const columns = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 70
  },
  {
    title: '组名',
    dataIndex: 'groupName',
    key: 'groupName',
    align: 'left',
    width: 220
  },
  {
    title: '组长',
    dataIndex: 'leaderName',
    key: 'leaderName',
    align: 'left',
    width: 220
  },
  {
    title: '团队成员',
    dataIndex: 'memberList',
    key: 'memberList',
    align: 'left'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: 220
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 100
  }
])
const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})
const modalOpen = ref(false)
const modalLoading = ref(false)
const paginationChange = (page: any) => {
  pagination.value = { ...page }
  loading.value = true
  getDataList()
}
const getDataList = () => {
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      if (v.dataIndex == 'createTime') {
        return Object.assign(c, {
          begin: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:ss') : '',
          end: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:ss') : ''
        })
      } else {
        return Object.assign(c, { [v.dataIndex]: v.value })
      }
    } else {
      return c
    }
  }, {})
  imgroupPage({
    ...obj,
    page: pagination.value.current,
    limit: pagination.value.pageSize
  })
    .then((res) => {
      List.value = res.data.list
      pagination.value.total = res.data.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
const getAllUserFun = async () => {
  await getAllUser().then(async (res) => {
    creatorList.value = []
    creatorListTwo.value = []
    res.data.forEach((item) => {
      creatorList.value.push({
        value: item.id,
        // label: item.realName + ' ' + item.workerCategory + ' ' + item.mobile
        label: item.realName,
        disabled: false
      })
      creatorListTwo.value.push({
        value: item.id,
        label: item.realName,
        disabled: false
      })
    })
    console.log(creatorList.value)
  })
}

const filterOption = (value, option) => {
  return option.label.toUpperCase().indexOf(value.toUpperCase()) >= 0
}

onMounted(() => {
  loading.value = true
  getDataList()
  getAllUserFun()
})
const onDelete = (data) => {}
const dropdownVisibleChange = (num) => {
  if (num == 1) {
    if (formState.otherMembers && formState.otherMembers.length > 0) {
      for (let i = 0; i < creatorList.value.length; i++) {
        creatorList.value[i].disabled = false
        for (let j = 0; j < formState.otherMembers.length; j++) {
          if (creatorList.value[i].value == formState.otherMembers[j]) {
            creatorList.value[i].disabled = true
          }
        }
      }
    } else {
      for (let i = 0; i < creatorList.value.length; i++) {
        creatorList.value[i].disabled = false
      }
    }
  } else {
    if (formState.groupLeader) {
      for (let i = 0; i < creatorListTwo.value.length; i++) {
        creatorListTwo.value[i].disabled = false
        if (formState.groupLeader == creatorListTwo.value[i].value) {
          creatorListTwo.value[i].disabled = true
        }
      }
    } else {
      for (let i = 0; i < creatorListTwo.value.length; i++) {
        creatorListTwo.value[i].disabled = false
      }
    }
  }
}

const memberList = (data) => {
  let menbers = []
  if (data && data.length > 0) {
    const list = data.map((item) => {
      if (item.memberId) {
        return item.memberName
      }
      return false
    })
    menbers = list.join(',')
  } else {
    menbers = ''
  }
  return menbers
}
const searchHandle = () => {
  pagination.value.current = 1
  loading.value = true
  getDataList()
}
const reset = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  loading.value = true
  getDataList()
  getAllUserFun()
}
const addOrUpdateHandle = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  modalOpen.value = true
}
const modalConfirm = () => {
  formRef.value.validate().then(() => {
    const param = {
      groupName: formState.groupName,
      groupLeaderId: formState.groupLeader,
      groupLeaderName: '',
      members: []
    }
    for (let i = 0; i < creatorListTwo.value.length; i++) {
      for (let j = 0; j < formState.otherMembers.length; j++) {
        const obj = {}
        if (formState.groupLeader == creatorListTwo.value[i].value) {
          param.groupLeaderName = creatorListTwo.value[i].label
        }
        if (formState.groupLeader == formState.otherMembers[j]) {
          message.error('组长和成员不能重复选择')
          return false
        } else {
          if (formState.otherMembers[j] == creatorListTwo.value[i].value) {
            obj.memberId = creatorListTwo.value[i].value
            obj.memberName = creatorListTwo.value[i].label
            param.members.push(obj)
          }
        }
      }
    }
    modalLoading.value = true
    imgroupCreate(param)
      .then((res) => {
        modalLoading.value = false
        modalOpen.value = false
        message.success('发布成功')
        loading.value = true
        getDataList()
        getAllUserFun()
      })
      .catch((err) => {
        // modalOpen.value = false
        modalLoading.value = false
        // message.error(err.msg)
      })

    return false
  })
}
const patientInfoHandle = (data) => {
  showDetail.value = true
  nextTick(() => {
    patientInfoRef.value.init(data)
  })
}
const goBack = () => {
  showDetail.value = false
  loading.value = true
  console.log('返回的数据')
  getDataList()
}
</script>
<style lang="less" scoped>
::v-deep(.cards) {
  width: 100%;
  height: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;
}

.modalChat {
  .modelForm {
    ::v-deep(.ant-form-item) {
      .ant-form-item-label {
        text-align: right;

        .ant-form-item-required {
          text-align: right;
        }
      }
    }
  }
}
</style>
